package com.mzp.XbShop.service;

import com.mzp.XbShop.common.util.IdWorker;
import com.mzp.XbShop.common.util.SendMailUtil;
import com.mzp.XbShop.mapper.UserMapper;
import com.mzp.XbShop.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import java.util.Date;

@Service
public class UserService {
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private BCryptPasswordEncoder encoder;
    public void add(User user) {
       user.setIsDel(0);
       user.setCreatetime(new Date());
       user.setLastlogintime(new Date());
       user.setOrdertotal(0);
       user.setUpdatetime(new Date());
        user.setId(idWorker.nextId()+"");
        user.setPassword(encoder.encode(user.getPassword()));
        userMapper.save(user);

    }

    public User findByusername(User user) {
       return userMapper.findByUsername(user.getUsername());
    }

    public User findByEamil(User user) {
        return userMapper.findByEmail(user.getEmail());
    }


    public String sendMail(String email) throws MessagingException {
        String mzp = SendMailUtil.sendEmail(email, "mzp");
        return mzp;
    }

    public void update(User user) {
        user.setPassword(encoder.encode(user.getPassword()));
        userMapper.save(user);
    }

    public User findById(String id) {
        return userMapper.findById(id).get();
    }

    public void updateUser(User user) {
//        user.setPassword(encoder.encode(user.getPassword()));
        user.setPassword(user.getPassword());
        user.setAge(user.getAge());
        user.setIsDel(user.getIsDel());
        user.setLastlogintime(user.getLastlogintime());
        user.setOrdertotal(user.getOrdertotal());

         userMapper.save(user);
    }

    public void updatePassword(User user) {
        user.setPassword(encoder.encode(user.getPassword()));
        user.setPassword(user.getPassword());
        user.setAge(user.getAge());
        user.setIsDel(user.getIsDel());
        user.setLastlogintime(user.getLastlogintime());
        user.setOrdertotal(user.getOrdertotal());
        userMapper.save(user);
    }

    public User findByWxOpenId(String openid) {
       return userMapper.findByWechat(openid);
    }


    public void insert(User user) {
        userMapper.save(user);
    }
}
